<template>
	<page-meta :page-style="show ? 'overflow: hidden;' : ''"></page-meta>
	<view class="container">
		<u-popup :show="show" @close="close" mode="right" :duration="100" :closeOnClickOverlay="false">
			<view class="container-popup" @touchmove.stop.prevent="handlePopupTouchMove">
				<!-- 1. 自定义导航栏 -->
				<view class="custom-navbar" :style="{ paddingTop: (statusBarHeight * 2) + 'rpx' }">
					<view class="nav-left">
						<u-icon name="arrow-left" size="22" @click="close"></u-icon>
						<u-avatar v-if="postDetail.avatar" :src="postDetail.avatar" size="30"
							customStyle="margin: 0 16rpx;" mode="aspectFill"
							@click="handleToPersonalHomepage(postDetail.userId)"></u-avatar>
						<view class="author-info-nav">
							<text class="author-name">{{ postDetail.nickName || '加载中...' }}</text>
							<!-- <view class="author-tag">
								<image src="/static/index/local/icon_gjtz.png" mode="heightFix"></image>
								<text>{{authorInfo.tag}}</text>
							</view> -->
						</view>
					</view>
					<view class="nav-right">
						<view class="level-right" v-if="!isFollowed" @click.stop="onFollow()">
							<u-icon name="plus" class="icon" :plain="true" size="14" shape="circle"
								color="#FE4E4E"></u-icon>关注
						</view>
						<view class="level-right active" v-if="isFollowed" @click.stop="onFollow()">
							<u-icon name="checkmark" class="icon" :plain="true" size="14" shape="circle"
								color="#ccc"></u-icon>已关注
						</view>
						<u-icon name="share-square" size="22" customStyle="margin-left: 20rpx;"></u-icon>
					</view>
				</view>

				<scroll-view class="main-content" scroll-y="true">
					<!-- 顶部媒体轮播 -->
					<view class="media-swiper-container">
						<!-- <u-swiper v-if="mediaList.length > 0" :list="mediaList" keyName="url"
							@change="e => swiperCurrent = e.current" :autoplay="false" indicator indicatorMode="dot"
							:height="swiperHeight" imgMode="aspectFill" radius="0" indicatorStyle="bottom:20rpx;"
							:lazy-load="true" :load-when-needed="true" indicatorActiveColor="#ffaa0c">
						</u-swiper> -->
						<u-swiper v-if="mediaList.length > 0" :list="mediaList" keyName="url"
							@change="e => swiperCurrent = e.current" :autoplay="false" indicator indicatorMode="dot"
							height="1000rpx" imgMode="aspectFill" radius="0" indicatorStyle="bottom:20rpx;"
							:lazy-load="true" :load-when-needed="true" indicatorActiveColor="#ffaa0c"
							@click="previewImage(swiperCurrent)">
						</u-swiper>
						<!-- 轮播图骨架屏 -->
						<u-skeleton v-else rows="0" title :avatar="false" loading height="1000rpx" titleHeight="450rpx"
							titleWidth="100%">
						</u-skeleton>
						<view class="swiper-indicator">{{ swiperCurrent + 1 }}/{{ mediaList.length }}</view>
					</view>

					<!-- 帖子内容 -->
					<view class="post-content-wrapper">
						<view class="post-title">{{ postDetail.title || '' }}</view>
						<view class="post-text">
							<text>{{ postDetail.content }}</text>
						</view>

						<view class="tags-section" v-if="postDetail.postTopics && postDetail.postTopics.length > 0">
							<text class="tag-item" v-for="(tag, index) in postDetail.postTopics"
								:key="index">#{{ tag.title }}</text>
						</view>

						<!-- 消费凭证 -->
						<view class="consumption-voucher" v-if="postDetail.isGood == 0">
							<view class="consumption-voucher-left">
								<view class="consumption-voucher-left-top">
									消费凭证
								</view>
								<view class="consumption-voucher-left-bottom">
									已通过平台审核，可作为参考
								</view>
							</view>

							<view class="consumption-voucher-right">
								<view class="consumption-voucher-right-show">
									<image src="/static/index/showDemo.png" mode=""></image>
									<view class="consumption-voucher-right-show-search">
										<u-icon name="search" color="rgba(255, 255, 255, 1)" size="26rpx"></u-icon>
									</view>
								</view>
								<view class="consumption-voucher-right-add">
									<image src="/static/index/addDemo.png" mode=""></image>
									<view class="consumption-voucher-right-show-add">
										+5
									</view>
								</view>
							</view>
						</view>

						<view class="publish-info">
							<text>发布于 {{ formatDate(postDetail.createTime) }}</text>
							<text class="location-text">{{ formatLocation(postDetail.location) }}</text>
						</view>
					</view>

					<!-- 打赏模块 -->
					<view class="tip">
						<!-- 		<view class="tip-top-img">
							<image src="/static/tip/tip-header.png" mode=""></image>
						</view> -->
						<view class="tip-top-title">
							"您的鼓励，是我的动力"
						</view>
						<view class="tip-middle" @click="TipListPopup = true" v-if="reversedTipList.length > 0">
							<view class="tip-middle-left" v-for="(tipListItem, index) in reversedTipList" :key="index"
								:style="{ zIndex: index, marginLeft: index === 0 ? '0' : '-10rpx' }">
								<image :src="tipListItem.clientUser.avatar || '/static/logo.png'" mode="aspectFill">
								</image>
							</view>
							<view class="tip-middle-right">
								<view class="tip-middle-right-left">
									{{ reversedTipList.length | formatLikes }}
								</view>
								<view class="tip-middle-right-right">人打赏</view>
							</view>
						</view>
						<view class="tip-footer" @click="handleOpenTip()">
							打赏
						</view>
					</view>

					<!-- 猜你也想去 -->
					<view class="highlight-section"
						v-if="postDetail.clientSpotsList &&postDetail.clientSpotsList.length > 0">
						<view class="section-title">
							<text class="section-title-text">猜你也想去</text>
							<image class="section-title-img" src="/static/index/homeDetailUnderLine.png" mode="">
							</image>
							<image class="section-title-img-person" src="/static/index/homeDetailRightPerson.png"
								mode=""></image>
						</view>
						<view class="highlight-list">
							<view class="highlight-item" v-for="item in postDetail.clientSpotsList" :key="item.id"
								@click="handleToAdress(item)">
								<image :src="item.imgUrl" mode="aspectFill" class="item-image" :lazy-load="true"
									@load="onImageLoad(`highlight-${item.id}`)"
									@error="onImageError(`highlight-${item.id}`)">
								</image>
								<view class="item-info">
									<view class="item-title-row">
										<text class="item-title">{{ item.spotName }}</text>
										<u-tag v-if="item.tag" :text="item.tag.text" :borderColor="item.tag.borderColor"
											color="#fa3534" size="mini" shape="circle" plain></u-tag>
									</view>
									<view class="item-distance">
										<text class="indexIconFont icon-dw"></text>
										<view class="distance">
											距你{{ item.distance || '未知' }}
										</view>
									</view>
									<!-- <text class="item-related">相关帖子 {{ item.relatedPosts }}+</text> -->
									<view class="item-address">
										<view class="address">
											地址：{{ item.address }}
										</view>
										<u-icon name="arrow-right" color="#cccccc" size="16"></u-icon>
									</view>
								</view>
							</view>
						</view>
					</view>
					<!-- 评论区 -->
					<view class="comment-section" id="comment-section">
						<view class="section-title comment-title">
							<text>评论 {{ tableTotal }}</text>
							<view class="view-count">
								<u-icon name="eye" color="#999" size="16"></u-icon>
								<text>浏览量 {{ postDetail.viewCount | formatLikes }}</text>
							</view>
						</view>

						<view v-for="(item,index) in tableData" :key="index" class="comment-view">
							<view class="comment-view-header" @click="handleReply(item)">
								<view class="comment-view-header-left">
									<view class="comment-view-header-avatar"
										@click.stop="handleToPersonalHomepage(item.userId)">
										<image :src="item.avatar?item.avatar:'/static/userAvatar.png'" mode=""></image>
									</view>
									<view class="comment-view-header-user_name">
										{{item.nickName}}
									</view>
									<view class="comment-view-header-tags" v-show="item.userId == postDetail.userId">
										作者
									</view>
								</view>
							</view>

							<view class="comment-view-content" @click="handleReply(item)">
								<view class="comment-view-content-left">
									{{item.content}}
								</view>

							</view>

							<view class="comment-view-footer">
								<view class="reply-time">{{ formatDate(item.createTime) }}</view>
								<view class="comment-view-footer-right">
									<view class="comment-view-footer-icon" @click="likeFun(item)">
										<u-icon :name="item.isLiked == 1 ? 'heart-fill' : 'heart'"
											:color="item.isLiked == 1 ? '#ff5050' : '#666'" size="20"></u-icon>
									</view>
									<view class="comment-view-footer-content">
										{{item.likeCount | formatLikes}}
									</view>
								</view>
							</view>

							<view class="comment-images-container" v-if="item.files && item.files.length > 0">
								<u-album :urls="item.files" keyName="fileUrl" multipleSize="180rpx" singleSize="180rpx"
									maxCount="3">
								</u-album>
							</view>

							<!-- 回复列表 -->
							<view class="reply-list" v-if="item.children && item.children.length > 0">
								<view class="reply-item" v-for="(reply, replyIndex) in item.children" :key="replyIndex">
									<view class="reply-header">
										<view class="reply-header-left">
											<view class="reply-avatar"
												@click.stop="handleToPersonalHomepage(reply.userId)">
												<image :src="reply.avatar?reply.avatar:'/static/userAvatar.png'"
													mode=""></image>
											</view>
											<view class="reply-user-info">
												<text class="reply-user-name">{{ reply.nickName }}</text>
												<text class="reply-user-tags"
													v-show="reply.userId == postDetail.userId">作者</text>
											</view>
										</view>

									</view>
									<view class="reply-content" @click="handleReply(item,reply)">
										<text v-if="reply.replyToName" class="reply-to-text">
											回复<span class="reply-target-user">{{ reply.replyToName }}</span>
										</text>
										<text class="reply-main-content">{{ reply.content }}</text>
									</view>
									<view class="reply-footer">
										<text class="reply-time">{{ formatDate(reply.createTime) }}</text>
										<view class="reply-action" @click="likeReply(reply)">
											<view class="reply-action-icon">
												<u-icon :name="reply.isLiked == 1 ? 'heart-fill' : 'heart'"
													:color="reply.isLiked == 1 ? '#ff5050' : '#999'" size="20"></u-icon>
											</view>
											<text>{{ reply.likeCount | formatLikes }}</text>
										</view>
									</view>
								</view>
							</view>
						</view>
						<!-- 评论输入框 -->
						<CommentInput :show="showComment" :duration="CommentDuration" :placeholder="commentPlaceholder"
							@close="closeComment" @open="openComment" @submit="handleCommentSubmit"
							:replyTarget="replyTarget" />
					</view>
				</scroll-view>
				<!-- 打赏弹框 -->
				<tipModel :show="showTipModal" :preData="postDetail" @close="showTipModal = false"></tipModel>
				<!-- 打赏列表弹框 -->

				<!-- 底部操作栏 -->
				<view class="bottom-bar">
					<view class="input-placeholder" @click="openComment">
						<u-icon name="edit-pen" color="#999" size="18"></u-icon>
						<text>说点什么吧...</text>
					</view>
					<view class="action-icons">

						<view class="icon-item" @click="handleLikePost">
							<view class="icon-item-top">
								<image
									:src="postDetail.isLiked ?'/static/index/detail/good-active.png' :'/static/index/detail/good.png'"
									mode=""></image>
							</view>
							<view class="icon-item-bottom">{{ postDetail.likeCount | formatLikes }}</view>
						</view>

						<view class="icon-item" @click="handleUnGood">
							<view class="icon-item-top">
								<image
									:src="postDetail.isStep ?'/static/index/detail/unGood-active.png' :'/static/index/detail/unGood.png'"
									mode=""></image>
							</view>
							<view class="icon-item-bottom">{{ postDetail.stepCount | formatLikes }}</view>
						</view>

						<view class="icon-item" @click="handleCollectPost">
							<view class="icon-item-top">
								<image
									:src="postDetail.isCollected ?'/static/index/detail/star-active.png' :'/static/index/detail/star.png'"
									mode=""></image>
							</view>
							<view class="icon-item-bottom">{{ postDetail.collectCount | formatLikes }}</view>
						</view>
					</view>
				</view>
			</view>
			<u-popup :show="TipListPopup" :round="10" mode="bottom" :closeable="true" @close="TipListPopup = false">
				<view class="TipListPopupStyle">
					<view class="header-title">
						打赏列表
					</view>
					<view class="content">
						<view class="content-item" v-for="(tips,tipIndex) in TipHoneyList" :key="tipIndex">
							<view class="content-item-left">
								<view class="content-item-avatar">
									<image :src="tips.clientUser.avatar" mode=""></image>
								</view>
								<view class="content-item-middle">
									<view class="content-item-middle-top">
										{{tips.clientUser.nickName}}
									</view>
									<view class="content-item-middle-bottom">
										打赏{{tips.clientUserHoney.honeyMoney}}蜂蜜值
										<image src="/static/index/wellet-fm.png" mode=""></image>
									</view>
								</view>
							</view>

							<view class="content-item-right">
								{{tips.clientUserHoney.honeyTime}}
							</view>
						</view>
					</view>
				</view>
			</u-popup>
		</u-popup>

	</view>
</template>

<script>
	import {
		getPostDetails,
		getClientFollow,
		getCommentList,
		addComment,
		postClientLike,
		postCancelLike,
		postClientCollect,
		postCancelCollect,
		addCommentLike,
		cancelCommentLike,
		clientStep,
		deleteClientStep,
		getPayHoneyUser,
		getCommentCount
	} from '@/request/api.js';
	import config from '@/config/index.js'
	import CommentInput from '@/components/commonComment/commonComment.vue';
	import CComment from "@/components/XJ-comment/index";
	import tipModel from "@/components/tipModel/tipModel";
	export default {
		name: "richPostDetail",
		components: {
			CommentInput,
			CComment,
			tipModel
		},
		props: {
			show: {
				type: Boolean,
				default: false,
			},
			postData: {
				type: Object,
				default: {}
			}
		},
		watch: {
			postData: {
				handler(newVal) {
					if (newVal && Object.keys(newVal).length > 0) {
						this.populatePageWithData(newVal);
						this.getPayList()
						// 进入页面，主要数据是由父组件传入的，内部的评论列表需要进入后单独请求
						this.fetchComments(newVal.id);
						this.looked(newVal.id)
						this.swiperCurrent = 0
						// 预加载首张图片以获取准确尺寸
						this.$nextTick(() => {
							if (this.mediaList.length > 0) {
								this.preloadFirstImage();
							}
						});
					}
				},
				immediate: true
			},
			show: {
				handler(newVal) {
					if (newVal) {
						// 弹窗打开时重新计算轮播图高度
						this.$nextTick(() => {
							this.calculateSwiperHeightWithImage();
						});
					}
				}
			}
		},
		filters: {
			formatLikes(val) {
				if (typeof val !== 'number') return val;
				if (val >= 10000) return (val / 10000).toFixed(1) + 'w';
				if (val >= 1000) return (val / 1000).toFixed(1) + 'k';
				return val;
			}
		},
		computed: {
			// ... 其他计算属性

			reversedTipList() {
				// 使用 Map 根据 clientUser.userId 去重
				const uniqueMap = new Map();
				this.TipHoneyList.forEach(item => {
					const userId = item.clientUser.userId;
					if (!uniqueMap.has(userId)) {
						uniqueMap.set(userId, item);
					}
				});

				// 转换为数组，取前6个并倒序
				const uniqueList = Array.from(uniqueMap.values());
				return uniqueList.slice(0, 6).reverse();
			}
		},
		data() {
			return {
				statusBarHeight: 0,
				systemInfo: null, // 系统信息
				authorInfo: {},
				postDetail: {},
				isFollowed: false,
				swiperHeight: '450rpx', // 添加默认高度
				swiperCurrent: 0,
				showComment: false,
				highlightedItems: [],
				tableData: [],
				mediaList: [],
				tableTotal: 0,
				CommentDuration: 300,
				// 图片加载状态管理
				imageLoadStatus: {},
				imageCache: {}, // 图片缓存
				// 添加当前位置属性
				currentLocation: {
					longitude: null,
					latitude: null
				},
				// 打赏列表
				showUploadOptions: false,
				replyTarget: null, // 添加回复目标参数
				commentPlaceholder: '爱评论的人运气都不差', // 评论框占位符
				// 打赏弹框
				showTipModal: false,
				// 打赏列表弹框
				TipListPopup: false,
				TipHoneyList: []
			};
		},
		created() {
			this.systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = this.systemInfo.statusBarHeight;

			this.getCurrentLocation();
		},

		methods: {
			looked(id){
				let params = {
					postId: id
				}
				getCommentCount(params).then(res => {
					console.log(res);
				})
			},
			getPayList() {
				let params = {
					userId: this.postData.userId,
					postId: this.postData.id
				}
				getPayHoneyUser(params).then(res => {
					if (res.data.code == 200) {
						this.TipHoneyList = res.data.data
					}
				})
			},
			handleToPersonalHomepage(userId) {
				uni.navigateTo({
					url: '/pages_sub/user/others/others?userId=' + userId
				})
			},
			handlePopupTouchMove(e) {
				// 阻止弹窗外层的触摸移动
				e.preventDefault();
			},
			// 打赏弹框
			handleOpenTip() {
				this.showTipModal = true
			},
			// 处理评论提交
			handleCommentSubmit(submitData) {
				const {
					content,
					files
				} = submitData;

				// 构建提交参数
				let params = {};

				// 如果是回复评论，添加回复相关参数
				if (this.replyTarget) {
					// 重置回复目标
					params = {
						content: content,
						files: files,
						...this.replyTarget
					}
					this.replyTarget = null;
					this.commentPlaceholder = '爱评论的人运气都不差';
				} else {
					// 直接评论
					params = {
						content: content,
						files: files,
						postId: this.postDetail.id,
						userId: this.$store.state.userInfo.userId,
						postCreatorId: this.postDetail.userId,
					}
				}

				// 调用API提交评论
				addComment(params).then(res => {
					if (res.data.code == 500) {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						});
					} else {
						// 评论成功，刷新评论列表
						this.fetchComments(this.postDetail.id);
						this.showComment = false;
					}
				});
			},
			showToast(message, icon = 'none') {
				uni.showToast({
					title: message,
					icon,
					duration: 3000
				});
			},

			// 预加载首张图片 (替代方案)
			preloadFirstImage() {
				if (this.mediaList.length > 0) {
					// 使用 uni.getImageInfo 获取图片信息，这也会触发图片加载
					uni.getImageInfo({
						src: this.mediaList[0].url,
						success: (info) => {
							// 图片信息获取成功后重新计算高度
							this.calculateSwiperHeightWithImage();
						},
						fail: (err) => {
							console.error('获取图片信息失败:', err);
							// 即使获取信息失败也尝试计算高度
							this.calculateSwiperHeightWithImage();
						}
					});
				}
			},
			// 图片加载成功回调
			onImageLoad(key) {
				this.$set(this.imageLoadStatus, key, 'loaded');
			},

			// 图片加载失败回调
			onImageError(key) {
				this.$set(this.imageLoadStatus, key, 'error');
			},

			onFollow() {
				getClientFollow({
					userId: this.postDetail.userId
				}).then(() => {
					this.isFollowed = !this.isFollowed;
				});
			},
			async fetchComments(postId) {
				try {
					const res = await getCommentList(postId);
					this.tableTotal = Number(res.data.total) || 0;
					this.tableData = res.data.rows || []
					console.log(this.tableData);
				} catch (error) {
					console.error("Fetch comments failed:", error);
				}
			},
			openComment() {
				this.CommentDuration = 600
				this.showComment = true
			},
			closeComment() {
				this.CommentDuration = 100
				this.showComment = false
				// 关闭评论框时重置回复目标
				this.replyTarget = null;
				this.commentPlaceholder = '爱评论的人运气都不差';
			},
			close() {
				this.$emit('close');
			},
			formatLocation(locationStr) {
				if (!locationStr) return '';
				const parts = locationStr.split('-');
				// 过滤掉空字符串
				const validParts = parts.filter(part => part && part.trim());

				// 只取前两级（省份和城市）
				if (validParts.length >= 2) {
					return validParts[0] + '-' + validParts[1];
				}

				// 如果不足两级，返回所有有效部分
				return validParts.join('-');
			},
			formatDate(dateStr) {
				return dateStr ? dateStr.split(' ')[0].replace(/-/g, '.') : '';
			},
			populatePageWithData(postData) {
				this.postDetail = postData;
				this.isFollowed = postData.isFollowed > 0;
				this.authorInfo = {
					id: postData.userId,
					nickName: postData.nickName,
					user_avatar: postData.avatar,
					tag: '高级土著'
				};
				this.mediaList = (postData.files || []).map(file => ({
					url: file.fileUrl,
					type: file.isImage ? 'image' : 'video'
				}));
				this.tableTotal = Number(this.commentCount) || 0;

				// 计算 swiper 高度
				this.$nextTick(() => {
					this.calculateSwiperHeightWithImage();
				});

				// 处理景点列表的距离计算
				if (postData.clientSpotsList && Array.isArray(postData.clientSpotsList)) {
					postData.clientSpotsList.forEach(item => {
						if (item.ext1) {
							// 使用 $set 确保响应式更新
							this.$set(item, 'distance', this.getDistance(item.ext1));
						}
					});
				}
			},

			// 解析坐标字符串并计算距离
			getDistance(ext1) {
				// 检查参数和当前位置
				if (!ext1 || !this.currentLocation.longitude || !this.currentLocation.latitude) {
					return '未知';
				}

				try {
					// 解析目标坐标
					const coords = ext1.split(',');
					if (coords.length !== 2) {
						return '未知';
					}

					const targetLat = parseFloat(coords[1].trim());
					const targetLng = parseFloat(coords[0].trim());

					if (isNaN(targetLat) || isNaN(targetLng)) {
						return '未知';
					}

					// 计算距离
					const distance = this.calculateDistance(
						this.currentLocation.latitude,
						this.currentLocation.longitude,
						targetLat,
						targetLng
					);

					return this.formatDistance(distance);
				} catch (error) {
					console.error('计算距离出错:', error);
					return '未知';
				}
			},
			previewImage(index) {
				console.log(index);
				if (!this.mediaList || this.mediaList.length === 0) return;

				// 提取所有图片URL
				const urls = this.mediaList
					.filter(item => item.type === 'image' || !item.type) // 默认认为没有type的也是图片
					.map(item => item.url);

				if (urls.length > 0) {
					uni.previewImage({
						urls: urls,
						current: index
					});
				}
			},
			// 获取当前位置
			getCurrentLocation() {
				// 先从缓存读取
				const longitude = uni.getStorageSync('longitude');
				const latitude = uni.getStorageSync('latitude');

				if (longitude && latitude) {
					this.currentLocation = {
						longitude: parseFloat(longitude),
						latitude: parseFloat(latitude)
					};
					console.log('从缓存获取位置:', this.currentLocation);
					return;
				}

				// 缓存没有则重新获取
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						this.currentLocation = {
							longitude: res.longitude,
							latitude: res.latitude
						};
						// 存储到缓存
						uni.setStorageSync('longitude', res.longitude);
						uni.setStorageSync('latitude', res.latitude);
						console.log('获取并存储位置:', this.currentLocation);
					},
					fail: (err) => {
						console.log('获取位置失败:', err);
						// 设置默认位置或标记为未知
						this.currentLocation = {
							longitude: null,
							latitude: null
						};
					}
				});
			},
			// 计算两点间距离（使用 Haversine 公式）
			calculateDistance(lat1, lon1, lat2, lon2) {
				const R = 6371; // 地球半径（公里）
				const dLat = this.toRadians(lat2 - lat1);
				const dLon = this.toRadians(lon2 - lon1);
				const a =
					Math.sin(dLat / 2) * Math.sin(dLat / 2) +
					Math.cos(this.toRadians(lat1)) * Math.cos(this.toRadians(lat2)) *
					Math.sin(dLon / 2) * Math.sin(dLon / 2);
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
				const d = R * c;
				return d;
			},
			// 角度转弧度
			toRadians(degrees) {
				return degrees * (Math.PI / 180);
			},

			// 格式化距离显示
			formatDistance(distance) {
				if (distance === null || distance === undefined) {
					return '未知';
				}

				if (distance < 1) {
					// 小于1公里显示米
					return Math.round(distance * 1000) + 'm';
				} else if (distance < 10) {
					// 1-10公里保留一位小数
					return distance.toFixed(1) + 'km';
				} else {
					// 大于10公里取整
					return Math.round(distance) + 'km';
				}
			},
			async fetchPostDetails(postId) {
				try {
					const res = await getPostDetails(postId);
					if (res.data && res.data.data) {
						this.populatePageWithData(res.data.data);
					}
				} catch (error) {
					console.error("Fetch post details failed:", error);
				}
			},

			handleToAdress(item) {
				// 解析目标坐标
				const coords = item.ext1.split(',');
				if (coords.length !== 2) {
					return '未知';
				}
				const targetLat = parseFloat(coords[1].trim());
				const targetLng = parseFloat(coords[0].trim());
				uni.openLocation({
					latitude: targetLat, //纬度
					longitude: targetLng, //经度
					name: item.spotName,
					address: ""
				});
			},

			handleCollectPost() {
				const isCollected = this.postDetail.isCollected;
				const api = isCollected ? postCancelCollect : postClientCollect;

				this.postDetail.isCollected = !isCollected;
				this.postDetail.collectCount += isCollected ? -1 : 1;

				api(this.postDetail.id).catch(() => {
					this.postDetail.isCollected = isCollected;
					this.postDetail.collectCount += isCollected ? 1 : -1;
				});
			},

			handleLikePost() {
				const isLiked = this.postDetail.isLiked;
				const api = isLiked ? postCancelLike : postClientLike;

				// UI即时反馈
				this.postDetail.isLiked = !isLiked;
				this.postDetail.likeCount += isLiked ? -1 : 1;

				api({
					postId: this.postDetail.id,
					userId: this.$store.state.userInfo.userId
				}).catch(() => {
					// 失败时回滚
					this.postDetail.isLiked = isLiked;
					this.postDetail.likeCount += isLiked ? 1 : -1;
				});
			},
			handleUnGood() {
				const isStep = this.postDetail.isStep;
				const api = !isStep ? clientStep : deleteClientStep;

				// UI即时反馈
				this.postDetail.isStep = !isStep;
				this.postDetail.stepCount += isStep ? -1 : 1;

				api({
					postId: this.postDetail.id,
					userId: this.$store.state.userInfo.userId
				}).catch(() => {
					// 失败时回滚
					this.postDetail.isStep = isStep;
					this.postDetail.likeCount += isStep ? 1 : -1;
				});
			},
			handleLikeComment() {

			},

			// 点赞评论
			likeFun(params) {
				console.log(params);
				if (params.isLiked == 0) {
					addCommentLike(params.commentId).then(res => {
						if (res.data.code != 200) {} else {
							this.fetchComments(this.postDetail.id);
						}
					})
				} else {
					cancelCommentLike(params.commentId).then(res => {
						if (res.data.code != 200) {} else {
							this.fetchComments(this.postDetail.id);
						}
					})
				}
			},

			// 点赞回复
			likeReply(params) {
				console.log(params);
				if (params.isLiked == 0) {
					addCommentLike(params.commentId).then(res => {
						if (res.data.code != 200) {} else {
							this.fetchComments(this.postDetail.id);
						}
					})
				} else {
					cancelCommentLike(params.commentId).then(res => {
						if (res.data.code != 200) {} else {
							this.fetchComments(this.postDetail.id);
						}
					})
				}
			},

			// 回复评论
			handleReply(target, parentComment = null) {
				// 设置回复目标
				this.replyTarget = {
					postId: target.postId,
					userId: this.$store.state.userInfo.userId,
					parentId: target.commentId,
					replyToUserId: parentComment ? parentComment.userId : target.userId,
					postCreatorId: target.userId,
					nickName: parentComment ? parentComment.nickName : target.nickName
				};
				// 更新评论框占位符
				this.commentPlaceholder = `回复 @${parentComment ? parentComment.nickName : target.nickName}`;
				// 打开评论框
				this.openComment();
			},

			sendParent(type) {
				// 触发父页面监听的 "returnData" 事件，回传数据
				const eventChannel = this.getOpenerEventChannel();
				eventChannel.emit('returnData', {
					id: this.postId,
					userId: this.authorInfo.id,
					type: type,
					isLiked: this.postDetail.isLiked,
					likeCount: this.postDetail.likeCount,
					isCollected: this.postDetail.isCollected,
					collectCount: this.postDetail.collectCount,
					isFollowed: this.postDetail.isFollowed
				});
			},

			// 删除评论
			deleteFun({
				params,
				mode
			}, callback) {
				// 当请求成功, 调用callback执行评论删除;
				switch (this.deleteMode) {
					case "bind":
						// 逻辑: 调用接口进行评论内容修改 update
						setTimeout(() => callback(), 500); // 目前为了展示效果, 直接执行callback
						break;
					case "only":
						// 逻辑: 调用接口删除一个评论 delete
						setTimeout(() => callback(), 500); // 目前为了展示效果, 直接执行callback
						break;
					case "both":
						// 逻辑: 调用接口删除一个评论 delete
						setTimeout(() => callback(), 500); // 目前为了展示效果, 直接执行callback
						break;
					default:
						break;
				}
			},

			// 计算轮播图高度（基于图片宽高比）
			calculateSwiperHeightWithImage() {
				if (this.mediaList.length === 0) {
					this.swiperHeight = '450rpx';
					return;
				}

				// 获取屏幕宽度
				const screenWidth = this.systemInfo.screenWidth || 375; // 默认375px
				const screenWidthPx = screenWidth;
				const screenWidthRpx = screenWidthPx * (750 / screenWidth); // 转换为rpx

				// 假设图片宽高比为4:3
				const aspectRatio = 4 / 3;
				const calculatedHeightRpx = screenWidthRpx / aspectRatio;

				// 设置最大和最小高度限制
				const minHeight = 400; // 最小高度400rpx
				const maxHeight = 800; // 最大高度800rpx

				let finalHeight = Math.max(minHeight, Math.min(maxHeight, calculatedHeightRpx));
				this.swiperHeight = `${finalHeight}rpx`;
			}
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		.container-popup {
			width: 100vw;
			height: 100vh;
			background-color: #fff;
			display: flex;
			flex-direction: column;

			.custom-navbar {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 16rpx 32rpx;
				border-bottom: 1rpx solid #f5f5f5;
				background-color: #fff;
				z-index: 999;
				flex-shrink: 0;

				.nav-left {
					display: flex;
					align-items: center;
					flex: 1;

					.author-info-nav {
						display: flex;
						flex-direction: column;

						.author-name {
							font-size: 32rpx;
							font-weight: 600;
							color: #333;
							line-height: 1.2;
						}

						.author-tag {
							display: flex;
							align-items: center;
							margin-top: 4rpx;

							image {
								height: 24rpx;
								margin-right: 8rpx;
							}

							text {
								font-size: 20rpx;
								color: #999;
							}
						}
					}
				}

				.nav-right {
					display: flex;
					align-items: center;

					.level-right {
						display: flex;
						align-items: center;
						justify-content: center;
						width: 120rpx;
						height: 48rpx;
						background: #FFFFFF;
						border: 1rpx solid #FE4E4E;
						border-radius: 24rpx;
						font-size: 24rpx;
						font-weight: 400;
						color: #FE4E4E;
						line-height: 48rpx;

						.icon {
							margin-right: 8rpx;
						}

						&.active {
							border: 1rpx solid #CCCCCC;
							color: #CCCCCC;
						}
					}
				}
			}

			.main-content {
				flex: 1;
				overflow: hidden;
			}

			.media-swiper-container {
				position: relative;
				background-color: #f8f8f8;

				.swiper-indicator {
					position: absolute;
					right: 32rpx;
					bottom: 32rpx;
					background: rgba(0, 0, 0, 0.5);
					color: white;
					padding: 8rpx 16rpx;
					border-radius: 20rpx;
					font-size: 24rpx;
					z-index: 10;
				}
			}

			.post-content-wrapper {
				padding: 32rpx;

				.post-title {
					font-size: 36rpx;
					font-weight: 600;
					color: #333;
					line-height: 1.4;
					margin-bottom: 24rpx;
				}

				.post-text {
					font-size: 30rpx;
					color: #666;
					line-height: 1.6;
					margin-bottom: 24rpx;
				}

				.tags-section {
					display: flex;
					flex-wrap: wrap;
					gap: 16rpx;
					margin-bottom: 24rpx;

					.tag-item {
						font-size: 24rpx;
						color: #ffaa0c;
						background: rgba(255, 170, 12, 0.1);
						padding: 8rpx 16rpx;
						border-radius: 8rpx;
					}
				}

				.publish-info {
					display: flex;
					align-items: center;
					justify-content: space-between;
					font-size: 24rpx;
					color: #999;

					.location-text {
						flex-shrink: 0;
						margin-left: 16rpx;
					}
				}
			}

			.consumption-voucher {
				width: 686rpx;
				height: 160rpx;
				background: rgba(255, 170, 12, 0.05);
				border-radius: 16rpx;
				margin: 0 auto;
				margin-bottom: 32rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 32rpx;

				.consumption-voucher-left {
					width: 60%;

					.consumption-voucher-left-top {
						font-size: 32rpx;
						font-weight: 600;
						color: #333333;
						line-height: 44rpx;
						margin-bottom: 8rpx;
					}

					.consumption-voucher-left-bottom {
						font-size: 24rpx;
						font-weight: 400;
						color: #999999;
						line-height: 33rpx;
					}
				}

				.consumption-voucher-right {
					display: flex;
					align-items: center;

					.consumption-voucher-right-show {
						width: 120rpx;
						height: 120rpx;
						background: #000000;
						border-radius: 16rpx;
						position: relative;
						margin-right: 16rpx;

						image {
							width: 100%;
							height: 100%;
							border-radius: 16rpx;
						}

						.consumption-voucher-right-show-search {
							position: absolute;
							top: 50%;
							left: 50%;
							transform: translate(-50%, -50%);
							width: 48rpx;
							height: 48rpx;
							background: rgba(0, 0, 0, 0.5);
							border-radius: 50%;
							display: flex;
							align-items: center;
							justify-content: center;
						}
					}

					.consumption-voucher-right-add {
						width: 120rpx;
						height: 120rpx;
						background: #D8D8D8;
						border-radius: 16rpx;
						position: relative;

						image {
							width: 100%;
							height: 100%;
							border-radius: 16rpx;
						}

						.consumption-voucher-right-show-add {
							position: absolute;
							top: 50%;
							left: 50%;
							transform: translate(-50%, -50%);
							font-size: 32rpx;
							font-weight: 600;
							color: #FFFFFF;
							line-height: 44rpx;
						}
					}
				}
			}

			// 打赏
			.tip {
				display: flex;
				flex-direction: column;
				align-items: center;

				.tip-top-img {
					width: 160rpx;
					height: 120rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}

				.tip-top-title {
					margin-top: 30rpx;
					font-weight: 400;
					font-size: 30rpx;
					line-height: 24rpx;
					color: #4d4d56;
				}

				.tip-middle {
					display: flex;
					justify-content: center;
					align-items: center;
					width: 100%;
					margin-top: 30rpx;

					.tip-middle-left {
						width: 44rpx;
						height: 44rpx;
						flex-shrink: 0;
						position: relative;
						border: 2rpx solid #fff; // 添加白色边框让重叠更明显
						border-radius: 50%;
						overflow: hidden;

						image {
							width: 100%;
							height: 100%;
							border-radius: 50%;
						}

						&:not(:first-child) {
							margin-left: -20rpx; // 重叠效果
						}
					}

					.tip-middle-right {
						display: flex;
						font-size: 24rpx;
						font-weight: 400;
						white-space: nowrap;
						flex-shrink: 0;
						margin-left: 10rpx;

						.tip-middle-right-left {
							color: rgba(252, 80, 36, 1);
						}

						.tip-middle-right-right {
							color: rgba(77, 77, 86, 1);
						}
					}
				}

				.tip-footer {
					width: 110rpx;
					height: 50rpx;
					font-size: 30rpx;
					line-height: 50rpx;
					font-weight: bold;
					color: rgba(255, 255, 255, 1);
					background-color: rgba(254, 119, 46, 1);
					border-radius: 20rpx;
					text-align: center;
					margin-top: 30rpx;
					margin-bottom: 30rpx;
				}
			}

			.highlight-section {
				padding: 0 32rpx 32rpx;

				.section-title {
					display: flex;
					align-items: center;
					margin-bottom: 24rpx;
					position: relative;
					padding-bottom: 40rpx;
					/* 为图片预留空间 */

					.section-title-text {
						font-size: 32rpx;
						font-weight: 600;
						color: #333;
						margin-right: 16rpx;
						z-index: 11;
					}

					.section-title-img {
						position: absolute;
						bottom: 30rpx;
						left: 0;
						width: 200rpx;
						height: 40rpx;
						z-index: 10;
					}

					.section-title-img-person {
						position: absolute;
						bottom: 46rpx;
						left: 160rpx;
						width: 44rpx;
						height: 44rpx;
						z-index: 10;
					}
				}

				.highlight-list {
					.highlight-item {
						display: flex;
						padding: 24rpx;
						background: #f8f8f8;
						border-radius: 16rpx;
						margin-bottom: 24rpx;

						&:last-child {
							margin-bottom: 0;
						}

						.item-image {
							width: 160rpx;
							height: 160rpx;
							border-radius: 12rpx;
							flex-shrink: 0;
							margin-right: 24rpx;
						}

						.item-info {
							flex: 1;
							display: flex;
							flex-direction: column;
							justify-content: space-between;

							.item-title-row {
								display: flex;
								align-items: center;
								justify-content: space-between;
								margin-bottom: 12rpx;

								.item-title {
									font-size: 28rpx;
									font-weight: 600;
									color: #333;
									flex: 1;
									margin-right: 16rpx;
								}
							}

							.item-distance {
								display: flex;
								align-items: center;
								margin-bottom: 12rpx;

								.icon-dw {
									font-size: 24rpx;
									color: #999;
									margin-right: 8rpx;
								}

								.distance {
									font-size: 24rpx;
									color: #999;
								}
							}

							.item-related {
								font-size: 24rpx;
								color: #ffaa0c;
								margin-bottom: 12rpx;
							}

							.item-address {
								display: flex;
								align-items: center;
								justify-content: space-between;

								.address {
									font-size: 24rpx;
									color: #666;
									flex: 1;
									margin-right: 16rpx;
								}
							}
						}
					}
				}
			}

			.comment-section {
				padding: 0 32rpx 160rpx;

				.section-title {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-bottom: 24rpx;

					&.comment-title {
						padding-top: 32rpx;
						border-top: 1rpx solid #f5f5f5;
					}

					text {
						font-size: 32rpx;
						font-weight: 600;
						color: #333;
					}

					.view-count {
						display: flex;
						align-items: center;
						font-size: 24rpx;
						color: #999;

						text {
							margin-left: 8rpx;
						}
					}
				}

				.comment-view {
					padding: 24rpx 0;
					border-bottom: 1rpx solid #f5f5f5;

					&:last-child {
						border-bottom: none;
					}

					.comment-view-header {
						display: flex;
						align-items: center;
						justify-content: space-between;
						margin-bottom: 16rpx;

						.comment-view-header-left {
							display: flex;
							align-items: center;

							.comment-view-header-avatar {
								width: 64rpx;
								height: 64rpx;
								border-radius: 50%;
								overflow: hidden;
								margin-right: 8rpx;

								image {
									width: 100%;
									height: 100%;
								}
							}

							.comment-view-header-user_name {
								font-size: 28rpx;
								font-weight: 500;
								color: #333;
								margin-right: 12rpx;
							}

							.comment-view-header-tags {
								height: 32rpx;
								background: rgba(255, 170, 12, 0.1);
								border-radius: 6rpx;
								font-size: 20rpx;
								font-weight: 400;
								color: #FFAA0C;
								line-height: 32rpx;
								padding: 0 12rpx;
							}
						}


					}

					.comment-view-content {
						display: flex;
						align-items: flex-start;
						justify-content: space-between;
						margin-bottom: 16rpx;
						margin-left: 70rpx;

						.comment-view-content-left {
							flex: 1;
							font-size: 28rpx;
							color: #333;
							line-height: 1.5;
							margin-right: 16rpx;
						}


					}

					.comment-images-container {
						margin-bottom: 16rpx;
					}

					.comment-view-footer {
						margin-left: 70rpx;
						color: rgba(25, 41, 28, 0.6);
						font-size: 18rpx;
						display: flex;
						justify-content: center;
						/* 水平居中 */
						align-items: center;
						/* 垂直居中 */

						.comment-view-footer-right {
							min-width: 100rpx;

							.comment-view-footer-icon {
								display: flex;
								align-items: center;
								justify-content: center;
							}

							.comment-view-footer-content {
								font-size: 24rpx;
								color: #999;
								text-align: center;
							}
						}
					}

					// 回复列表样式
					.reply-list {
						margin-top: 16rpx;
						padding: 16rpx 0 0 70rpx;
						border-radius: 12rpx;

						.reply-item {
							padding: 12rpx 0;
							border-bottom: 1rpx solid #eee;

							&:last-child {
								border-bottom: none;
							}

							.reply-header {
								display: flex;
								align-items: center;
								margin-bottom: 8rpx;
								justify-content: space-between;

								.reply-header-left {
									display: flex;

									.reply-avatar {
										width: 48rpx;
										height: 48rpx;
										border-radius: 50%;
										overflow: hidden;
										margin-right: 12rpx;

										image {
											width: 100%;
											height: 100%;
										}
									}

									.reply-user-info {
										display: flex;
										align-items: center;

										.reply-user-name {
											font-size: 24rpx;
											font-weight: 500;
											color: #333;
											margin-right: 8rpx;
										}

										.reply-user-tags {
											height: 24rpx;
											background: rgba(255, 170, 12, 0.1);
											border-radius: 4rpx;
											font-size: 18rpx;
											font-weight: 400;
											color: #FFAA0C;
											line-height: 24rpx;
											padding: 0 8rpx;
										}
									}
								}


							}

							.reply-content {
								font-size: 26rpx;
								color: #333;
								line-height: 1.4;
								margin-bottom: 8rpx;
								word-wrap: break-word;
								word-break: break-all;
							}

							.reply-to-text {
								color: #999;
								margin-right: 8rpx;
							}

							.reply-target-user {
								color: #ffaa0c;
								margin: 0 8rpx;
							}

							.reply-main-content {
								color: #333;
							}

							.reply-footer {
								display: flex;
								align-items: center;
								justify-content: space-between;

								.reply-time {
									font-size: 22rpx;
									color: #999;
								}


								.reply-action {
									min-width: 100rpx;
									font-size: 22rpx;
									color: #999;
									text-align: center;

									.reply-action-icon {
										display: flex;
										justify-content: center;
									}
								}

								.reply-action-comment {
									margin-left: 24rpx;
								}
							}
						}
					}

					.comment-view-footer {
						display: flex;
						align-items: center;
						justify-content: space-between;

						.comment-time {
							font-size: 24rpx;
							color: #999;
						}

						.comment-actions {
							display: flex;
							align-items: center;

							.comment-action {
								display: flex;
								align-items: center;
								margin-left: 24rpx;
								font-size: 24rpx;
								color: #999;

								text {
									margin-left: 8rpx;
								}
							}
						}
					}
				}
			}

			.bottom-bar {
				position: fixed;
				bottom: 0;
				left: 0;
				right: 0;
				background: #fff;
				padding: 20rpx 32rpx;
				border-top: 1rpx solid #f5f5f5;
				display: flex;
				align-items: center;
				justify-content: space-between;
				z-index: 1000;

				.input-placeholder {
					flex: 1;
					height: 72rpx;
					background: #f8f8f8;
					border-radius: 36rpx;
					display: flex;
					align-items: center;
					padding: 0 24rpx;
					font-size: 28rpx;
					color: #999;

					text {
						margin-left: 12rpx;
					}
				}

				.action-icons {
					display: flex;
					align-items: center;
					margin-left: 24rpx;

					.icon-item {
						display: flex;
						flex-direction: column;
						align-items: center;
						margin-left: 32rpx;

						&:first-child {
							margin-left: 0;
						}

						.icon-item-top {
							width: 48rpx;
							height: 48rpx;
							margin-bottom: 8rpx;

							image {
								width: 100%;
								height: 100%;
							}
						}

						.icon-item-bottom {
							font-size: 20rpx;
							color: #999;
						}
					}
				}
			}
		}

		.TipListPopupStyle {
			.header-title {
				text-align: center;
				font-size: 30rpx;
				line-height: 30rpx;
				color: #000000;
				margin: 50rpx 0;
			}

			.content {
				.content-item {
					height: 120rpx;
					border-bottom: 1px solid #2929300D;
					margin: 0 30rpx 20rpx;
					display: flex;
					justify-content: space-between;

					.content-item-left {
						display: flex;

						.content-item-avatar {
							width: 90rpx;
							height: 90rpx;

							image {
								border-radius: 50%;
								width: 100%;
								height: 100%;
							}
						}

						.content-item-middle {
							margin-left: 20rpx;

							.content-item-middle-top {
								font-size: 30rpx;
								font-weight: bold;
								height: 45rpx;
								line-height: 45rpx;
							}

							.content-item-middle-bottom {
								font-size: 24rpx;
								color: #787882;
								height: 45rpx;
								line-height: 45rpx;

								image {
									width: 32rpx;
									height: 32rpx;
								}
							}
						}
					}

					.content-item-right {
						color: #787882;
						font-size: 26rpx;
						line-height: 90rpx;
					}
				}
			}
		}
	}
</style>